/**
 * 动态路由处理
 * 根据接口返回的菜单列表注册动态路由
 */
import type { Router, RouteRecordRaw } from 'vue-router'
import type { AppRouteRecord } from '@/types/router'
import { saveIframeRoutes } from './menuToRouter'
import { RoutesAlias } from '../routesAlias'
import { h } from 'vue'
import { useMenuStore } from '@/store/modules/menu'

/**
 * 动态导入 views 目录下所有 .vue 组件
 */
const modules: Record<string, () => Promise<any>> = import.meta.glob('../../views/**/*.vue')

/**
 * 注册异步路由
 * 将接口返回的菜单列表转换为 Vue Router 路由配置，并添加到传入的 router 实例中
 * @param router Vue Router 实例
 * @param menuList 接口返回的菜单列表
 */
export function registerDynamicRoutes(router: Router, menuList: AppRouteRecord[]): void {
  console.log('[Route Register] 开始注册动态路由，菜单列表:', menuList);
  console.log('[Route Register] 可用的模块路径:', Object.keys(modules));
  
  // 用于局部收集 iframe 类型路由
  const iframeRoutes: AppRouteRecord[] = []
  // 收集路由移除函数
  const removeRouteFns: (() => void)[] = []

  // 检测菜单列表中是否有重复路由
  checkDuplicateRoutes(menuList)

  // 遍历菜单列表，注册路由
  menuList.forEach((route) => {
    // 只有还没注册过的路由才进行注册
    if (route.name && !router.hasRoute(route.name)) {
      console.log('[Route Register] 正在注册路由:', route.name, route.path);
      const routeConfig = convertRouteComponent(route, iframeRoutes)
      console.log('[Route Register] 路由配置:', routeConfig);
      // addRoute 返回移除函数，收集起来
      const removeRouteFn = router.addRoute(routeConfig as RouteRecordRaw)
      removeRouteFns.push(removeRouteFn)
    } else if (route.name) {
      console.log('[Route Register] 路由已存在，跳过注册:', route.name);
    }
  })

  // 将移除函数存储到 store 中
  const menuStore = useMenuStore()
  menuStore.addRemoveRouteFns(removeRouteFns)

  // 保存 iframe 路由
  saveIframeRoutes(iframeRoutes)
  console.log('[Route Register] 动态路由注册完成');
}

/**
 * 路径解析函数：处理父路径和子路径的拼接
 */
function resolvePath(parent: string, child: string): string {
  // 如果child路径已经包含了parent路径前缀，则直接返回child
  if (parent && child.startsWith(parent)) {
    return child;
  }
  
  // 否则正常拼接路径
  const parentPath = parent.replace(/\/$/, ''); // 移除父路径末尾的斜杠
  const childPath = child.replace(/^\//, '');  // 移除子路径开头的斜杠
  return [parentPath, childPath].filter(Boolean).join('/');
}

/**
 * 检测菜单中的重复路由（包括子路由）
 */
function checkDuplicateRoutes(routes: AppRouteRecord[], parentPath = ''): void {
  // 用于检测动态路由中的重复项
  const routeNameMap = new Map<string, string>() // 路由名称 -> 路径
  const componentPathMap = new Map<string, string>() // 组件路径 -> 路由信息

  const checkRoutes = (routes: AppRouteRecord[], parentPath = '') => {
    routes.forEach((route) => {
      // 处理路径拼接，避免重复
      const currentPath = route.path || '';
      const fullPath = parentPath && !currentPath.startsWith(parentPath) 
        ? resolvePath(parentPath, currentPath) 
        : currentPath;
      
      // 名称重复检测
      if (route.name) {
        if (routeNameMap.has(String(route.name))) {
        } else {
          routeNameMap.set(String(route.name), fullPath)
        }
      }

      // 组件路径重复检测
      if (route.component) {
        const componentPath = getComponentPathString(route.component)

        if (componentPath && componentPath !== RoutesAlias.Layout) {
          // 使用实际的组件路径而不是完整路径进行重复检查
          const componentKey = componentPath;
          
          if (componentPathMap.has(componentKey)) {
          } else {
            componentPathMap.set(componentKey, fullPath)
          }
        }
      }

      // 递归处理子路由
      if (route.children?.length) {
        checkRoutes(route.children, fullPath)
      }
    })
  }

  checkRoutes(routes, parentPath)
}

/**
 * 获取组件路径的字符串表示
 */
function getComponentPathString(component: any): string {
  if (typeof component === 'string') {
    return component
  }

  // 对于其他别名路由，获取组件名称
  for (const key in RoutesAlias) {
    if (RoutesAlias[key as keyof typeof RoutesAlias] === component) {
      return `RoutesAlias.${key}`
    }
  }

  return ''
}

/**
 * 根据组件路径动态加载组件
 * @param componentPath 组件路径（不包含 ../../views 前缀和 .vue 后缀）
 * @param routeName 当前路由名称（用于错误提示）
 * @returns 组件加载函数
 */
function loadComponent(componentPath: string, routeName: string): () => Promise<any> {
  // 如果路径为空，直接返回一个空的组件
  if (componentPath === '') {
    console.warn(`[Route Register] 组件路径为空，使用空组件: ${routeName}`);
    return () =>
      Promise.resolve({
        render() {
          return h('div', {})
        }
      })
  }

  console.log(`[Route Register] 尝试加载组件: ${componentPath} (路由: ${routeName})`);

  // 特殊处理一些常见的路径模式，避免重复层级
  let finalComponentPath = componentPath;
  // 处理类似 integralGoodsMall/integralGoodsMall/integralGoods 的情况
  const pathParts = componentPath.split('/');
  if (pathParts.length >= 2 && pathParts[0] === pathParts[1]) {
    // 移除重复的部分
    finalComponentPath = pathParts.filter((part, index) => index === 0 || part !== pathParts[index-1]).join('/');
  }
  
  // 处理以 @/views 开头的绝对路径
  if (finalComponentPath.startsWith('@/views/')) {
    const absolutePath = finalComponentPath.replace('@/views/', '../../views/');
    console.log(`[Route Register] 处理绝对路径: ${finalComponentPath} -> ${absolutePath}`);
    
    // 首先尝试直接路径
    if (modules[absolutePath]) {
      console.log(`[Route Register] 成功加载组件: ${absolutePath} (路由: ${routeName})`);
      return modules[absolutePath];
    }
    
    // 如果直接路径不存在，尝试添加 /index.vue 后缀
    const indexPath = absolutePath.replace('.vue', '/index.vue');
    if (modules[indexPath]) {
      console.log(`[Route Register] 成功加载组件: ${indexPath} (路由: ${routeName})`);
      return modules[indexPath];
    }
    
    console.error(`[Route Register] 组件未找到: ${absolutePath} 或 ${indexPath} (路由: ${routeName})`);
    return () =>
      Promise.resolve({
        render() {
          return h('div', `组件未找到: ${routeName} (${absolutePath})`)
        }
      })
  }
  
  // 构建可能的路径
  const fullPath = `../../views/${finalComponentPath}.vue`;
  const fullPathWithIndex = `../../views/${finalComponentPath}/index.vue`;

  console.log(`[Route Register] 尝试路径: ${fullPath}`);
  console.log(`[Route Register] 尝试路径: ${fullPathWithIndex}`);

  // 先尝试直接路径，再尝试添加/index的路径
  const module = modules[fullPath] || modules[fullPathWithIndex]

  if (!module) {
    console.error(`[Route Register] 组件未找到: ${fullPath} 或 ${fullPathWithIndex} (路由: ${routeName})`);
    return () =>
      Promise.resolve({
        render() {
          return h('div', `组件未找到: ${routeName}`)
        }
      })
  }

  console.log(`[Route Register] 成功加载组件: ${fullPath} (路由: ${routeName})`);
  return module
}

/**
 * 转换后的路由配置类型
 */
interface ConvertedRoute extends Omit<RouteRecordRaw, 'children'> {
  id?: number
  children?: ConvertedRoute[]
  component?: RouteRecordRaw['component'] | (() => Promise<any>)
}

/**
 * 转换路由组件配置
 */
function convertRouteComponent(
  route: AppRouteRecord,
  iframeRoutes: AppRouteRecord[],
  depth = 0
): ConvertedRoute {
  const { component, children, ...routeConfig } = route

  // 基础路由配置
  const converted: ConvertedRoute = {
    ...routeConfig,
    component: undefined
  }

  // 是否为一级菜单
 const isFirstLevel = depth === 0 && component !== RoutesAlias.Layout && component !== 'Layout'

  console.log(`[Route Register] 处理路由: ${route.name}, 组件: ${component}, 深度: ${depth}, 是否一级菜单: ${isFirstLevel}`);

  if (route.meta.isIframe) {
    handleIframeRoute(converted, route, iframeRoutes, depth)
  } else if (isFirstLevel) {
    handleLayoutRoute(converted, route, component as string)
  } else {
    handleNormalRoute(converted, component as string, String(route.name))
  }

  // 递归时增加深度
  if (children?.length) {
    converted.children = children.map((child) =>
      convertRouteComponent(child, iframeRoutes, depth + 1)
    )
  }

  console.log(`[Route Register] 转换完成的路由配置:`, converted);
  return converted
}

/**
 * 处理 iframe 类型路由
 */
function handleIframeRoute(
  targetRoute: ConvertedRoute,
  sourceRoute: AppRouteRecord,
  iframeRoutes: AppRouteRecord[],
  depth: number
): void {
  const LAYOUT_VIEW = () => import('@/views/index/index.vue')
  const IFRAME_VIEW = () => import('@/views/outside/Iframe.vue')

  if (depth === 0) {
    // 顶级 iframe：用 Layout 包裹
    targetRoute.component = LAYOUT_VIEW
    targetRoute.path = `/${(sourceRoute.path?.split('/')[1] || '').trim()}`
    targetRoute.name = ''

    targetRoute.children = [
      {
        ...sourceRoute,
        component: IFRAME_VIEW
      } as ConvertedRoute
    ]
  } else {
    // 非顶级（嵌套）iframe：直接使用 Iframe.vue
    targetRoute.component = IFRAME_VIEW
  }

  // 记录 iframe 路由，供 Iframe.vue 查找对应的外链
  iframeRoutes.push(sourceRoute)
}

/**
 * 处理一级菜单路由
 */
function handleLayoutRoute(
  converted: ConvertedRoute,
  route: AppRouteRecord,
  component: string | undefined
): void {
  converted.component = () => import('@/views/index/index.vue')
  converted.path = `/${(route.path?.split('/')[1] || '').trim()}`
  converted.name = ''
  route.meta.isFirstLevel = true

  console.log(`[Route Register] 处理一级菜单路由: ${route.name}, 组件路径: ${component}`);
  
  // 只有当 component 不是 Layout 时才创建子路由
  if (component && component !== 'Layout') {
    converted.children = [
      {
        ...route,
        component: loadComponent(component as string, String(route.name))
      } as ConvertedRoute
    ]
  } else {
    // 如果是 Layout 类型，直接使用原始路由配置
    converted.children = route.children ? route.children.map(child => ({
      ...child,
      component: child.component ? loadComponent(child.component as string, String(child.name)) : undefined
    })) : []
  }
}

/**
 * 处理普通路由
 */
function handleNormalRoute(
  converted: ConvertedRoute,
  component: string | undefined,
  routeName: string
): void {
  console.log(`[Route Register] 处理普通路由: ${routeName}, 组件路径: ${component}`);
  if (component) {
    // 特殊处理 Layout 组件别名
    if (component === RoutesAlias.Layout || component === '/index/index') {
      console.log(`[Route Register] 使用 Layout 组件: ${component}`);
      converted.component = () => import('@/views/index/index.vue');
      return;
    }
    
    const aliasComponent = RoutesAlias[
      component as keyof typeof RoutesAlias
    ] as unknown as RouteRecordRaw['component']
    if (aliasComponent) {
      console.log(`[Route Register] 使用别名组件: ${component}`);
      converted.component = aliasComponent;
    } else {
      console.log(`[Route Register] 使用动态加载组件: ${component}`);
      converted.component = loadComponent(component as string, routeName)
    }
  } else {
    console.warn(`[Route Register] 路由 "${routeName}" 没有指定组件`);
    // 如果没有组件，提供一个默认的空组件
    converted.component = () => Promise.resolve({
      render() {
        return h('div', `未配置组件的路由: ${routeName}`)
      }
    });
  }
}